import axios from "axios";
import router from '@/router/index.js';
import { Message } from "element-ui";
import { getToken, removeToken } from '@/utils/auth'
const service = axios.create({
  timeout: 20000 // 请求超时时间
});

// request拦截器，
service.interceptors.request.use(
  config => {
    // 权限校验
    var sysToken = getToken();
    if (sysToken && sysToken.length > 0) {
      config.headers['Authorization'] = sysToken
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
// response拦截器，
service.interceptors.response.use(
  response => {
    if (response.config.responseType === 'blob') {

      if (response.status != 200) {

        Message.error('请求失败' + response.status);
        return Promise.reject()
      } else if (!response.headers["content-disposition"]) {

        Message.error('暂无接口访问权限');
        return Promise.reject()
      }
      return response

    } else {

      if (response.data.code !== 0) {
        let errMsg = response.data.msg;
        if (response.data.code == 401) { // token失效
          if (getToken()) {
            Message.error(errMsg);
            removeToken()
            router.replace('/Login')
          }
        } else {
          Message.error(errMsg);
        }
        return Promise.reject(errMsg)
      }
      return response.data;
    }

  },
  error => {
    Message.error('请求资源错误，请稍后再试');
    return Promise.reject(error);
  }
);

export default service
